﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.Net;
using System.IO;

namespace AutoNyaa.Logic.Entities
{
    [Serializable]
    [XmlRoot("channel")]
    public class RssFeed
    {
        public static RssFeed Deserialize(Uri url, int page = 0, string search = "", string category = "0_0", string filter = "0")
        {
            try
            {
                WebClient client = new WebClient();
                string feed = client.DownloadString(url + "&cats=" + category + "&filter=" + filter + "&term=" + search + "&offset=" + page + "&sort=1&order=1");

                return RssFeed.Deserialize(feed);
            }
            catch (Exception)
            {
                return null;
            }
        }
        public static RssFeed Deserialize(string rss)
        {
            RssFeed feed = null;
            XmlTextReader reader = null;
            StringReader stringReader = null;

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(RssFeed));

                stringReader = new StringReader(rss);

                reader = new XmlTextReader(stringReader);
                reader.ReadToDescendant("channel");
                feed = (RssFeed)serializer.Deserialize(reader);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
            }
            return feed;
        }

        [XmlElement("title")]
        public string Title { get; set; }

        [XmlElement("link")]
        public string Link { get; set; }

        [XmlElement("atom:link")]
        public string AtomLink { get; set; }

        [XmlElement("description")]
        public string Description { get; set; }

        [XmlElement("item")]
        public List<Item> Items { get; set; }
    }
}